/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Desarrollo.Soft.Hibernate.ViewPrincipal.views;

import Desarrollo.Soft.Hibernate.Control.Consultas.ctrlCompras;
import Desarrollo.Soft.Hibernate.Data.Entity.Tblproveedores;
import Desarrollo.Soft.Hibernate.Control.ctrlGeneric;
import Desarrollo.Soft.Hibernate.Data.Entity.Tblcompras;
import Desarrollo.Soft.Hibernate.Data.Entity.Tblcomprasproductos;
import Desarrollo.Soft.Hibernate.Data.Entity.Tblproductosproveedores;
import Desarrollo.Soft.Hibernate.ViewPrincipal.frmPantallaPrincipal;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;

/**
 *
 * @author Suriel
 */
public class intFrmCompra extends javax.swing.JInternalFrame {

    /**
     * Creates new form intFrmCompra
     */
    private frmPantallaPrincipal pantallaPrincipal;
    private List<Tblproveedores> listaProveedores;
    DefaultTableModel tablaCompras = new DefaultTableModel();
    private List<Tblcomprasproductos> lista = new ArrayList<Tblcomprasproductos>();

    public intFrmCompra() {
        initComponents();

        Date now = new Date(System.currentTimeMillis());
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat hour = new SimpleDateFormat("HH:mm:ss");
        txtFecha.setText(date.format(now));
        txtHora.setText(hour.format(now));

        String titulosProductos[] = {"NÚM DE PRODUCTO", "NOMBRE", "CODIGO", "U. MEDIDA", "PRECIO COMPRA", "CANTIDAD", "TOTAL"};
        tablaCompras.setColumnIdentifiers(titulosProductos);
        this.tblCompras.setModel(tablaCompras);

        this.cargarCombo();
        this.generarFolio();
    }

    public intFrmCompra(frmPantallaPrincipal _pantallaPrincipal) {
        initComponents();
        this.pantallaPrincipal = _pantallaPrincipal;


        Date now = new Date(System.currentTimeMillis());
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat hour = new SimpleDateFormat("HH:mm:ss");
        txtFecha.setText(date.format(now));
        txtHora.setText(hour.format(now));

        String titulosProductos[] = {"NÚM DE PRODUCTO", "NOMBRE", "CODIGO", "U. MEDIDA", "PRECIO COMPRA", "CANTIDAD", "TOTAL"};
        tablaCompras.setColumnIdentifiers(titulosProductos);
        this.tblCompras.setModel(tablaCompras);

        this.cargarCombo();
        this.generarFolio();
    }

    private void cargarCombo() {
        try {
            List<Tblproveedores> listaProveedores = ctrlGeneric.<Tblproveedores>selectItems(Tblproveedores.class);

            comboProveedor.removeAllItems();
            for (int i = 0; i < listaProveedores.size(); i++) {
                comboProveedor.addItem(listaProveedores.get(i).getNombeproveedor());
            }
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
    }

    private void generarFolio() {
        ctrlCompras compras = new ctrlCompras();
        String folio = "";
        Date now = new Date(System.currentTimeMillis());
        SimpleDateFormat fol = new SimpleDateFormat("HHmmss");
        do {
            for (int x = 1; x <= 2; x++) {
                Random r = new Random();
                int valorDado = r.nextInt(10) + 1;
                folio = folio + valorDado;
            }
        } while (compras.verificarFolio() == true);
        txtFolioCompra.setText(fol.format(now) + folio);
    }

    public void agregarProducto(Tblcomprasproductos _productos) {
        try {
            lista.add(_productos);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    public void cargarProductos() {
        try {

            for (int i = tblCompras.getRowCount() - 1; i >= 0; i--) {
                tablaCompras.removeRow(i);
            }
            for (int i = 0; i < lista.size(); i++) {
                String[] arr = new String[6];
                arr[0] = String.valueOf(lista.get(i).getCatproductos().getId());
                arr[1] = lista.get(i).getCatproductos().getDescripcion();
                arr[2] = lista.get(i).getCatproductos().getValor();
                arr[3] = lista.get(i).getUnidadmedida();
                arr[4] = String.valueOf(lista.get(i).getPreciocompra());
                arr[5] = String.valueOf(lista.get(i).getCantidadProducto());
                arr[6] = String.valueOf(lista.get(i).getPreciototal());

                tablaCompras.addRow(arr);
            }
            tblCompras.setModel(tablaCompras);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

  

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel15 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        txtFolioCompra = new javax.swing.JTextField();
        jLabel17 = new javax.swing.JLabel();
        txtFecha = new javax.swing.JTextField();
        txtHora = new javax.swing.JTextField();
        jLabel19 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        comboProveedor = new javax.swing.JComboBox();
        btnAgregarProducto = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCompras = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        txtIva = new javax.swing.JTextField();
        txtTotal = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        jLabel15.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
        jLabel15.setText("Compras");

        jLabel14.setText("Folio:");

        txtFolioCompra.setEditable(false);

        jLabel17.setText("Fecha");

        txtFecha.setEditable(false);

        txtHora.setEditable(false);

        jLabel19.setText("Hora");

        jLabel16.setText("Proveedor:");

        btnAgregarProducto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Desarrollo/Soft/Hibernate/ViewPrincipal/Imagenes/Add.gif"))); // NOI18N
        btnAgregarProducto.setText("Agregar Productos");
        btnAgregarProducto.setFocusable(false);
        btnAgregarProducto.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAgregarProducto.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAgregarProducto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarProductoActionPerformed(evt);
            }
        });

        tblCompras.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tblCompras);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Desarrollo/Soft/Hibernate/ViewPrincipal/Imagenes/Accept.gif"))); // NOI18N
        jButton1.setText("Aceptar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Desarrollo/Soft/Hibernate/ViewPrincipal/Imagenes/Delete.gif"))); // NOI18N
        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("IVA");

        jLabel2.setText("TOTAL");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(99, 99, 99)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(106, 106, 106)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtIva, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
                    .addComponent(txtTotal))
                .addGap(175, 175, 175))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(567, 567, 567)
                        .addComponent(jLabel15))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(80, 80, 80)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1088, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(93, 93, 93)
                        .addComponent(jLabel16)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel14)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtFolioCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel17)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(58, 58, 58)
                                .addComponent(jLabel19)
                                .addGap(18, 18, 18)
                                .addComponent(txtHora, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(57, 57, 57))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(comboProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 490, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(210, 210, 210)
                                .addComponent(btnAgregarProducto)))))
                .addContainerGap(66, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(jLabel15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(410, 410, 410)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtIva, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel17)
                            .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel19)
                            .addComponent(txtHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel14)
                            .addComponent(txtFolioCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(51, 51, 51)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(comboProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel16))
                            .addComponent(btnAgregarProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(47, 47, 47)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(41, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarProductoActionPerformed
        try {
            this.pantallaPrincipal.agregarCompraProducto(this);
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
    }//GEN-LAST:event_btnAgregarProductoActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        Date now = new Date(System.currentTimeMillis());
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat hour = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat dateDos = new SimpleDateFormat("yyyyMMdd");
        tablaCompras.setRowCount(0);

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            Double totalCompleto = Double.parseDouble(txtTotal.getText());
            Tblcompras comp = new Tblcompras();
            if (totalCompleto > 0) {
                Date now = new Date(System.currentTimeMillis());
                SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat hour = new SimpleDateFormat("HH:mm:ss");
                SimpleDateFormat dateDos = new SimpleDateFormat("yyyyMMdd");

                txtFecha.setText(date.format(now));
                txtHora.setText(hour.format(now));

                String fecha = txtFecha.getText();
                String hora = txtHora.getText();

                try {
                    for (int i = 0; i < tblCompras.getRowCount(); i++) {
                        comp.setFolio(txtFolioCompra.getText());
                        comp.setFechacompra(Date.valueOf(txtFecha.getText()+"-"+txtHora.getText()));
                        comp.setTotalcompra(Double.parseDouble(txtTotal.getText()));
                        comp.setTblproveedores(listaProveedores.get(comboProveedor.getSelectedIndex()-1));
                        ctrlGeneric.<Tblcompras>createItem(comp);
                    }
                } catch (HibernateException ex) {
                }
                txtFecha.setText(date.format(now));
                txtHora.setText(hour.format(now));

                tablaCompras.setRowCount(0);

                JOptionPane.showMessageDialog(null, "Los datos de la compra se han guardado correctamente");
            } else {
                JOptionPane.showMessageDialog(null, "No se puede agregar una compra de $0.0");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error al insertar los datos", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregarProducto;
    private javax.swing.JComboBox comboProveedor;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblCompras;
    private javax.swing.JTextField txtFecha;
    private javax.swing.JTextField txtFolioCompra;
    private javax.swing.JTextField txtHora;
    private javax.swing.JTextField txtIva;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables
}
